/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.spakehelpdesk.session;

import com.spakehelpdesk.entity.Department;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.jms.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author leehoanh
 */
@Stateless
@LocalBean
public class DepartmentSession {
    @Resource(mappedName = "jms/Notification/Queue")
    private Queue notificationQueue;
    @Resource(mappedName = "jms/Notification/QueueFactory")
    private ConnectionFactory notificationQueueFactory;
    @PersistenceContext(unitName = "Spake_Helpdesk-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    
    //select all department in company
    public List<Department> getAll()
    {
        Query query = em.createNamedQuery("Department.findAll");
        try {
            return query.getResultList();
        } catch (Exception e) {
            return null;
        }
        
    }
    //select depatment by department name
    public Department getDepartmentByName(String name) {
        Query query = em.createNamedQuery("Department.findByDepartmentName");
        query.setParameter("departmentName", name);
        try {
            return (Department)query.getResultList();
        } catch (Exception e) {
            return null;
        }
    }
    //select depatment by department id
    public Department getDepartmentById(int Id) {
        Query query = em.createNamedQuery("Department.findByDepartmentID");
        query.setParameter("departmentID", Id);
        try {
            return (Department)query.getResultList();
        } catch (Exception e) {
            return null;
        }
    }
    //Update or edit a department

    public Department updateDepartment(Department department) {
        Department updated = em.merge(department);
        try {
            sendJMSMessageToQueue(updated);//send task update to queue
        } catch (JMSException ex) {
            Logger.getLogger(AccountSession.class.getName()).log(Level.SEVERE, null, ex);
        }
        return updated;
    }
     //create a new Department

    public boolean createNewDepartment(Department department) {
        boolean result = false;
        //check the exist of department by department name
        if (getDepartmentByName(department.getDepartmentName()) == null) {
            em.persist(department);//create
            result = true;
        } else 
        {
            result = false;//account is existed 
        }
        return result;
    }

    private Message createJMSMessageForjmsNotificationQueue(Session session, Object messageData) throws JMSException {
        // TODO create and populate message to send
        TextMessage tm = session.createTextMessage();
        tm.setText(messageData.toString());
        return tm;
    }

    private void sendJMSMessageToQueue(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = notificationQueueFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(notificationQueue);
            messageProducer.send(createJMSMessageForjmsNotificationQueue(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
    
}
